// 简化版 Markdown 编辑器
class SimpleMDEditor {
    constructor(element, options = {}) {
        this.element = element;
        this.options = {
            placeholder: options.placeholder || '在此输入 Markdown 内容...',
            value: options.value || '',
            ...options
        };
        
        this.init();
    }
    
    init() {
        this.createEditor();
        this.bindEvents();
    }
    
    createEditor() {
        this.element.innerHTML = `
            <div class="simple-md-editor">
                <div class="toolbar bg-gray-50 border-b border-gray-200 p-2 rounded-t-lg">
                    <div class="flex flex-wrap gap-1">
                        <button type="button" data-action="bold" class="toolbar-btn" title="加粗 (Ctrl+B)">
                            <i class="fas fa-bold"></i>
                        </button>
                        <button type="button" data-action="italic" class="toolbar-btn" title="斜体 (Ctrl+I)">
                            <i class="fas fa-italic"></i>
                        </button>
                        <button type="button" data-action="heading" class="toolbar-btn" title="标题">
                            <i class="fas fa-heading"></i>
                        </button>
                        <div class="w-px bg-gray-300 mx-1"></div>
                        <button type="button" data-action="quote" class="toolbar-btn" title="引用">
                            <i class="fas fa-quote-right"></i>
                        </button>
                        <button type="button" data-action="list-ul" class="toolbar-btn" title="无序列表">
                            <i class="fas fa-list-ul"></i>
                        </button>
                        <button type="button" data-action="list-ol" class="toolbar-btn" title="有序列表">
                            <i class="fas fa-list-ol"></i>
                        </button>
                        <div class="w-px bg-gray-300 mx-1"></div>
                        <button type="button" data-action="link" class="toolbar-btn" title="链接">
                            <i class="fas fa-link"></i>
                        </button>
                        <button type="button" data-action="image" class="toolbar-btn" title="图片">
                            <i class="fas fa-image"></i>
                        </button>
                        <button type="button" data-action="code" class="toolbar-btn" title="代码">
                            <i class="fas fa-code"></i>
                        </button>
                        <div class="w-px bg-gray-300 mx-1"></div>
                        <button type="button" data-action="preview" class="toolbar-btn" title="预览">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button type="button" data-action="fullscreen" class="toolbar-btn" title="全屏">
                            <i class="fas fa-expand"></i>
                        </button>
                    </div>
                </div>
                <div class="editor-container">
                    <textarea class="editor-textarea w-full p-4 border-0 resize-none focus:outline-none" 
                        placeholder="${this.options.placeholder}" rows="20">${this.options.value}</textarea>
                </div>
                <div class="preview-container hidden bg-gray-50 p-4 border-t border-gray-200 rounded-b-lg">
                    <div class="preview-content prose max-w-none"></div>
                </div>
            </div>
        `;
        
        this.textarea = this.element.querySelector('.editor-textarea');
        this.previewContainer = this.element.querySelector('.preview-container');
        this.previewContent = this.element.querySelector('.preview-content');
        this.toolbar = this.element.querySelector('.toolbar');
        
        // 设置初始值
        if (this.options.value) {
            this.textarea.value = this.options.value;
        }
    }
    
    bindEvents() {
        // 工具栏按钮事件
        this.element.addEventListener('click', (e) => {
            if (e.target.closest('.toolbar-btn')) {
                const action = e.target.closest('.toolbar-btn').dataset.action;
                this.handleToolbarAction(action);
            }
        });
        
        // 预览切换
        this.element.addEventListener('click', (e) => {
            if (e.target.closest('[data-action="preview"]')) {
                this.togglePreview();
            }
        });
        
        // 全屏切换
        this.element.addEventListener('click', (e) => {
            if (e.target.closest('[data-action="fullscreen"]')) {
                this.toggleFullscreen();
            }
        });
        
        // 实时预览
        this.textarea.addEventListener('input', () => {
            if (!this.previewContainer.classList.contains('hidden')) {
                this.updatePreview();
            }
        });
    }
    
    handleToolbarAction(action) {
        const textarea = this.textarea;
        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;
        const text = textarea.value;
        const selectedText = text.substring(start, end);
        
        let replacement = '';
        let newCursorPos = start;
        
        switch (action) {
            case 'bold':
                replacement = `**${selectedText}**`;
                newCursorPos = start + 2;
                break;
            case 'italic':
                replacement = `*${selectedText}*`;
                newCursorPos = start + 1;
                break;
            case 'heading':
                replacement = `# ${selectedText}`;
                newCursorPos = start + 2;
                break;
            case 'quote':
                replacement = `> ${selectedText}`;
                newCursorPos = start + 2;
                break;
            case 'list-ul':
                replacement = `- ${selectedText}`;
                newCursorPos = start + 2;
                break;
            case 'list-ol':
                replacement = `1. ${selectedText}`;
                newCursorPos = start + 3;
                break;
            case 'link':
                replacement = `[${selectedText}](URL)`;
                newCursorPos = start + selectedText.length + 3;
                break;
            case 'image':
                replacement = `![${selectedText}](图片URL)`;
                newCursorPos = start + selectedText.length + 5;
                break;
            case 'code':
                replacement = `\`${selectedText}\``;
                newCursorPos = start + 1;
                break;
        }
        
        if (replacement) {
            textarea.value = text.substring(0, start) + replacement + text.substring(end);
            textarea.setSelectionRange(newCursorPos, newCursorPos);
            textarea.focus();
        }
    }
    
    togglePreview() {
        const previewBtn = this.element.querySelector('[data-action="preview"]');
        const isHidden = this.previewContainer.classList.contains('hidden');
        
        if (isHidden) {
            this.previewContainer.classList.remove('hidden');
            this.updatePreview();
            previewBtn.innerHTML = '<i class="fas fa-edit"></i>';
            previewBtn.title = '编辑';
        } else {
            this.previewContainer.classList.add('hidden');
            previewBtn.innerHTML = '<i class="fas fa-eye"></i>';
            previewBtn.title = '预览';
        }
    }
    
    updatePreview() {
        const markdown = this.textarea.value;
        const html = this.markdownToHtml(markdown);
        this.previewContent.innerHTML = html;
    }
    
    markdownToHtml(markdown) {
        // 简单的 Markdown 转 HTML 实现
        return markdown
            .replace(/^### (.*$)/gim, '<h3>$1</h3>')
            .replace(/^## (.*$)/gim, '<h2>$1</h2>')
            .replace(/^# (.*$)/gim, '<h1>$1</h1>')
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
            .replace(/\*(.*?)\*/g, '<em>$1</em>')
            .replace(/`(.*?)`/g, '<code>$1</code>')
            .replace(/^> (.*$)/gim, '<blockquote>$1</blockquote>')
            .replace(/^- (.*$)/gim, '<ul><li>$1</li></ul>')
            .replace(/^1\. (.*$)/gim, '<ol><li>$1</li></ol>')
            .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>')
            .replace(/!\[([^\]]+)\]\(([^)]+)\)/g, '<img src="$2" alt="$1">')
            .replace(/\n/g, '<br>');
    }
    
    toggleFullscreen() {
        const fullscreenBtn = this.element.querySelector('[data-action="fullscreen"]');
        const isFullscreen = this.element.classList.contains('fullscreen');
        
        if (isFullscreen) {
            this.element.classList.remove('fullscreen');
            fullscreenBtn.innerHTML = '<i class="fas fa-expand"></i>';
            fullscreenBtn.title = '全屏';
        } else {
            this.element.classList.add('fullscreen');
            fullscreenBtn.innerHTML = '<i class="fas fa-compress"></i>';
            fullscreenBtn.title = '退出全屏';
        }
    }
    
    value() {
        return this.textarea.value;
    }
    
    setValue(value) {
        this.textarea.value = value || '';
    }
}

// 全局函数，兼容 EasyMDE 接口
window.EasyMDE = SimpleMDEditor;
